
from store.HouseStore import HouseStore
from store.XiaoquStore import XiaoquStore
from notify.HouseNotify import HouseNotify
from spider.ershou_spider import ErShouSpider
from task.CrawlHouse import CrawlHouse
from notify.item.HouseChangeItem import HouseChangeItem
from spider.base_spider import BaseSpider
from baseclass.send_email import SendMail
import traceback
from lib.utility.log import *

class MonitorLikeHouse:

    def __init__(self):
        self.house_store = HouseStore()
        self.xiaoqu_store = XiaoquStore()
        self.notify = HouseNotify()
        self.crawl_house = CrawlHouse()

    def monitor_like(self):
        change_list = []
        like_data = self.house_store.get_all_like_house()
        if not like_data or like_data is None:
            return
        logger.info("关注的房源共：{0}个".format(len(like_data)))
        self.do_crawl_target_house(like_data)

    def monitor_suitable_house(self,district=None,min_price=250,max_price=550,size=50,max_size=80,xiaoqu_id_list=[],must_look=None):
        change_list = []
        like_data = self.house_store.get_target_house(district,min_price,max_price,size,max_size,xiaoqu_id_list,must_look)
        if not like_data or like_data is None:
            return
        logger.info("符合要求的房源共：{0}个".format(len(like_data)))
        self.do_crawl_target_house(like_data)
        logger.info("房源爬取完毕.g共：{0}个".format(len(like_data)))

    def do_crawl_target_house(self,like_data):
        change_list = []
        for house_db in like_data:
            try:
                er_shou = self.crawl_house.crawl_house_detail("", house_db["xuequ_id"], house_db["xiaoqu_id"],
                                                              house_db["house_id"])
                if self.house_store.change_price(er_shou, house_db):
                    house_chane = HouseChangeItem(HouseChangeItem.CHANGE_PIRCE, er_shou, house_db["price"])
                    change_list.append(house_chane)
            except Exception as e:
                logger.error("爬取房源出现异常.house_id:{0}.e:{1}.有可能已经核销或者下架".format(house_db["house_id"],traceback.print_exc()),exc_info=traceback.print_exc())
                # mail = SendMail()
                # mail.send_email("房源爬取异常提醒.",msghtml="爬取房源出现异常.house_id:{0}.e:{1}".format(house_db["house_id"],traceback.print_exc()))
        self.notify.notify_change_house_list(change_list)

    def monitor_xiaoqu_like(self):
        change_list = []
        like_data = self.xiaoqu_store.get_all_like_house()
        if not like_data or like_data is None:
            return
        logger.info("关注的小区共：{0}个".format(len(like_data)))
        area_list = []
        for xiaoqu in like_data:
            if xiaoqu["xuequ_id"] not in area_list:
                area_list.append(xiaoqu["xuequ_id"])
                try:
                    self.crawl_house.spider.crawl_xiaoqu_list(xiaoqu["district"], xiaoqu["xuequ_id"])
                except:
                    mail = SendMail()
                    mail.send_email("房源小区异常提醒.",
                                    msghtml="房源小区异常提醒.xuequ_id:{0}.e:{1}".format(xiaoqu["xuequ_id"],
                                                                                         traceback.print_exc())
                                    )

        #爬取房源信息
        BaseSpider.random_delay()
        self.crawl_house.crawl_house_by_xiaoqu(id_list=[x['xiaoqu_id'] for x in like_data])

if __name__ == "__main__":
    like = MonitorLikeHouse()
    like.monitor_suitable_house(min_price=400,max_price=500,district="haidian")
